package org.elastic.compreplatform.admin.manager.sysuser.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.elastic.compreplatform.admin.common.constant.LoginEnum;
import org.elastic.compreplatform.admin.core.shiro.session.CustomSessionManager;
import org.elastic.compreplatform.admin.core.shiro.token.manager.TokenManager;
import org.elastic.compreplatform.admin.manager.sysuser.model.SysUser;
import org.elastic.compreplatform.admin.manager.sysuser.service.ISysUserService;
import org.elastic.compreplatform.codegener.model.SysConfig;
import org.elastic.compreplatform.codegener.service.ICodegenerService;
import org.elastic.compreplatform.common.model.RespMsg;
import org.elastic.compreplatform.common.util.CreateImageCode;
import org.elastic.compreplatform.common.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xiaoleilu.hutool.date.DateUtil;

import cn.org.codegenframework.generator.GeneratorFacade;
import cn.org.codegenframework.generator.GeneratorProperties;
import cn.org.codegenframework.generator.util.FileHelper;
import cn.org.codegenframework.generator.util.StringHelper;

/**
 * ClassName: SysUserController 
 * @Description: 用户操作控制类
 * @author JornTang
 * @date 2018年1月28日
 */
@Controller
@RequestMapping("/user")
public class SysUserController {
	private static Logger log = LoggerFactory.getLogger(SysUserController.class);
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private ICodegenerService codegenerService;
	@RequestMapping("/selectById")
	public void selectById() {
		SysUser obj = (SysUser)sysUserService.selectById(1);
		System.err.println();
	}
	/**
	 * @Description: 登录验证
	 * @param request
	 * @param session
	 * @param username
	 * @param password
	 * @param code
	 * @return
	 * @throws IOException   
	 * @return RespMsg  
	 * @throws
	 * @author JornTang
	 * @date 2018年1月28日
	 */
    @RequestMapping("/anon/loginCheck.do")
    @ResponseBody
    public RespMsg loginCheck(HttpServletRequest request, HttpSession session, String username, String password, String code, String rememberme)throws IOException {
        return TokenManager.loginCheck(username, password, code, rememberme, request);
    }
	/**
	 * @Description: 生成验证码
	 * @param response
	 * @param session
	 * @throws IOException   
	 * @return void  
	 * @throws
	 * @author JornTang
	 * @date 2018年1月28日
	 */
    @RequestMapping("/anon/captcha.do")
    public void captcha(HttpServletResponse response, HttpSession session)throws IOException {
        CreateImageCode vCode = new CreateImageCode(116,36,5,10);
        log.info("生成验证码:【{}】",vCode.getCode());
        session.setAttribute(LoginEnum.CAPTCHA_CODE.getCode(), vCode.getCode());
        vCode.write(response.getOutputStream());
    }
    /**
     * @Description: 跳转到登录页面
     * @param request
     * @param model
     * @return   
     * @return ModelAndView  
     * @throws
     * @author JornTang
     * @date 2018年1月29日
     */
	@RequestMapping("/anon/toLogin.do") 
	public ModelAndView toLogin(){
		ModelAndView view = new ModelAndView(); 
		//redirect:/login.jsp sysuser/login
		view.setViewName("redirect:/login.jsp");
		return view;
	}
	/**
     * @Description: 跳转到主页
     * @param request
     * @param model
     * @return   
     * @return ModelAndView  
     * @throws
     * @author JornTang
     * @date 2018年1月29日
     */
	@RequestMapping("/toDefault.do") 
	public ModelAndView toDefault(){
		ModelAndView view = new ModelAndView(); 
		view.setViewName("sysuser/default");
		view.addObject("userTotal", CustomSessionManager.getAllUser().size());
		return view;
	}
	/**
     * @Description: 跳转到未授权页面
     * @param request
     * @param model
     * @return   
     * @return ModelAndView  
     * @throws
     * @author JornTang
     * @date 2018年1月29日
     */
	@RequestMapping("/toUnauthorized.do") 
	public ModelAndView toUnauthorized(){
		ModelAndView view = new ModelAndView(); 
		view.setViewName("sysuser/unauthorized");
		return view;
	}
	/**
     * @Description: 跳转到踢出页面
     * @param request
     * @param model
     * @return   
     * @return ModelAndView  
     * @throws
     * @author JornTang
     * @date 2018年1月29日
     */
	@RequestMapping("/toKickout.do") 
	public ModelAndView toKickout(){
		ModelAndView view = new ModelAndView(); 
		view.setViewName("sysuser/kickout");
		return view;
	}
	/**
	 * @Description: 生成代码
	 * @param request
	 * @param SysConfig
	 * @return   
	 * @return RespMsg  
	 * @throws
	 * @author JornTang
	 * @date 2018年2月3日
	 */
	@RequestMapping(value="/codeBuild.do",method=RequestMethod.GET)
	public void codeBuild(HttpServletRequest request, HttpServletResponse response, Long id, String basepackage, String tableRemovePrefixes, String tableName){
		OutputStream out = null;
		try {
			//获取数据库配置
			SysConfig SysConfig = new SysConfig();
			SysConfig.setId(id);
			SysConfig config = codegenerService.searchDbconfById(SysConfig);
			//设置数据库相关属性
			GeneratorProperties.setProperty("namespace", basepackage);
			GeneratorProperties.setProperty("basepackage", basepackage);
			GeneratorProperties.setProperty("tableRemovePrefixes", tableRemovePrefixes);
			GeneratorProperties.setProperty("jdbc.username", config.getUsername());
			GeneratorProperties.setProperty("jdbc.password", config.getPassword());
			GeneratorProperties.setProperty("jdbc.url", config.getDbUrl());
			GeneratorProperties.setProperty("jdbc.driver", config.getDbDriver()); 
			GeneratorProperties.setProperty("jdbc.schema", config.getDbSchema());
			String buildPath = request.getServletContext().getRealPath("/") ;
			//String buildPath = this.getClass().getClassLoader().getResource("build").getPath(); 
			String outRoot = buildPath + "build" + "\\generator-output";
			GeneratorProperties.setProperty("outRoot", outRoot);
			GeneratorFacade g = new GeneratorFacade();
			//获取项目动态绝对路径 
			//String path = request.getServletContext().getRealPath("");
			//GeneratorProperties.setProperty("outRoot", path + "\\build\\generator-output");
			//g.deleteOutRootDir();
			//删除已输出的代码
			if (StringHelper.isBlank(outRoot)) {
				throw new IllegalStateException("'outRootDir' property must be not null.");
			} else {
				FileHelper.deleteDirectory(new File(outRoot));
			}
			//根据模板生成代码
			String templatePath = buildPath + "template";
			g.generateByTable(tableName, templatePath);
			File srcFile = new File(buildPath + "build");
			log.info("压缩包路径：{}", srcFile);
			//设置压缩包名称
			String zipName = DateUtil.format(new Date(), "yyyyMMddHHmmss")+"-templatecode.zip";
			response.setHeader("content-disposition", "attachment;filename="  
	                + URLEncoder.encode(zipName, "UTF-8"));
			out = response.getOutputStream();
			ZipUtil.zip(srcFile, out);
			
			//直接打开生成代码的文件
			//Runtime.getRuntime().exec("cmd.exe /c start " + GeneratorProperties.getRequiredProperty("outRoot"));
		} catch (Exception e) {
			log.error("生成代码异常",e);
		} finally {
			try {
				if(out!= null) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				log.error("HttpServletResponse输出流关闭异常", e);
			}
		}
	}
}
